<?php
class CheckresultModel extends Model{

	protected $fields = array('usr_id','agt_id','crt_rank','crt_lasttime');
	
	
	/**
	 * 给用户分配代理IP检测
	 * @param int $uid
	 */
	function alloc($uid) {
		$uInfo = D('Userinfo')->find($uid);
		if ($uInfo) {
			$time		=	time();
			$yesterday	=	$time - 24*3600;
			$completeCnt=	$this->where("usr_id=$uid AND crt_rank!=0 AND crt_lasttime>$yesterday")->count();
			
			$left = $uInfo['usi_number'] - $completeCnt;
			$left = min(8,$left);
			if ($left>0) {
				$result	=	D('Agent')->alias('A')
								->field('A.agt_id,agt_ip,agt_port,agt_type,crt_lasttime')
								->join(sprintf('LEFT JOIN %s as ME ON A.agt_id = ME.agt_id',$this->getTableName()))
								->where("agt_lasttime=0 AND agt_country='中国' and agt_province not in ('台湾','香港','澳门') AND (ME.usr_id= $uid AND ME.crt_rank=0 OR ME.crt_rank IS NULL)")
								->limit($left)->select();
				if ($result) {
					$ret = array();
					$addData = array();
					foreach ($result as $v) {
						if (0==$v['crt_lasttime']) {
							$addData[]	=	array(
								'usr_id'	=>	$uid,
								'agt_id'	=>	$v['agt_id'],
								'crt_lasttime'=>$time,
							);
						}
						unset($v['crt_lasttime']);
						$ret[] = $v;
					}
					if (!empty($addData)) {
						$this->addAll($addData);
					}
					return $ret;
				}
			}
		}
	}
	
	/**
	 * 合并结果 
	 */
	function merge($minCnt) {
		$lists = $this->select();
		$group = array();
		foreach ($lists as $v) {
			$agtId	=	$v['agt_id'];
			$rank	=	$v['crt_rank'];
			if (0==$rank) {
				continue;
			}
			if (!isset($group[$agtId])) {
				$group[$agtId]	=	array(
					'crt_lasttime'=>$v['crt_lasttime'],//最后更新时间
				);
			}
			if (isset($group[$agtId][$rank])) {
				++$group[$agtId][$rank];
			}else {
				$group[$agtId][$rank] = 1;
			}
			$group[$agtId]['crt_lasttime'] = max($v['crt_lasttime'],$group[$agtId]['crt_lasttime']);
		}
		$delAgtIds = array();//需要删除的agt代理IP
		foreach ($group as $agtId=>$agentResult){
			$trueRank = 0;
			$rankMaxCnt = 0;
			foreach ($agentResult as $rank => $rankCnt) {
				if (is_numeric($rank)) {
					if ($rankCnt>$rankMaxCnt) {
						$trueRank = $rank;
						$rankMaxCnt = $rankCnt;
					}
				}
			}
			if ($rankMaxCnt>=$minCnt) {
				$saveData = array('agt_lasttime'=>$agentResult['crt_lasttime'],'agt_checktime'=>$agentResult['crt_lasttime']);
				if (-1==$trueRank) {
					$saveData['agt_err'] = 1;
				}else {
					$saveData['agt_rank']	=	$trueRank;
				}
				D('Agent')->where(array('agt_id'=>$agtId,'agt_lasttime'=>0))->save($saveData);
				array_push($delAgtIds, $agtId);
			}
		}
		if (!empty($delAgtIds)) {
			$this->where(array('agt_id'=>array('IN',$delAgtIds)))->delete();
			//删除10天前的数据
			$this->where('crt_lasttime < '.(time()-10*24*3600))->delete();
		}
	}
}